# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
from scrapy.selector import Selector
from scrapy.http import FormRequest
import urllib

class DoubanSpider(scrapy.Spider):
    name = "douban"
    allowed_domains = ["douban.com"]
    start_urls = ['http://www.douban.com/']

    headers = {
        "Accept": "*/*",
        "Accept-Encoding": "gzip,deflate",
        "Accept-Language": "en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4",
        "Connection": "keep-alive",
        "Content-Type": " application/x-www-form-urlencoded; charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36",
        "Referer": "http://www.douban.com/"
    }

    def start_requests(self):
        print 'start .......'
        return [Request("https://accounts.douban.com/login",
                        meta={'cookiejar': 1},
                        callback=self.parse)]


    def parse(self, response):
        try:
            captcha = response.xpath("//img[@id='captcha_image]/@src").extract()
        except:
            captcha = []
        url = "https://accounts.douban.com/login"
        data = {
            "form_email": "lck5602@126.com",
            "form_password": "19891109lck",
            "redir": "https://movie.douban.com/"
        }
        if len(captcha):
            print ("验证码")
            localpath = 'capture.png'
            urllib.urlretrieve(captcha[0],filename=localpath)
            print "请输入验证码"
            image_data = input()
            data.update({
                "captcha_solution":image_data
            })


        return [FormRequest.from_response(response,
                                          meta={'cookiejar': response.meta['cookiejar']},
                                          headers=self.headers,
                                          formdata=data,
                                          callback=self.after_login)]

    def after_login(self,response):
        pass
